<!-- src/views/company/Dashboard.vue -->
<template>
  <div class="dashboard">
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card>
          <el-statistic title="发布岗位数" :value="stats.publishedPositions || 0" />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <el-statistic title="当前实习岗位数" :value="stats.activePositions || 0" />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <el-statistic title="收到申请数" :value="stats.totalApplications || 0" />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <el-statistic title="在岗实习生" :value="stats.currentInterns || 0" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 快捷操作 -->
    <el-row :gutter="20" class="actions-section">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>快捷操作</span>
            </div>
          </template>
          <div class="quick-actions">
            <el-button type="primary" @click="navigateTo('/company/positions')">
              发布新岗位
            </el-button>
            <el-button type="success" @click="navigateTo('/company/applications')">
              查看申请
            </el-button>
            <el-button type="warning" @click="navigateTo('/company/evaluations')">
              评分管理
            </el-button>
            <el-button type="info" @click="navigateTo('/company/profile')">
              企业信息
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近申请 -->
    <el-row :gutter="20" class="recent-applications">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>最近申请</span>
            </div>
          </template>
          <el-table :data="recentApplications" style="width: 100%">
            <el-table-column prop="studentName" label="申请人" />
            <el-table-column prop="positionTitle" label="申请岗位" />
            <el-table-column prop="appliedAt" label="申请时间">
              <template #default="scope">
                {{ formatDate(scope.row.appliedAt) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag :type="getApplicationStatusType(scope.row.status)">
                  {{ getApplicationStatusLabel(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button size="small" @click="navigateToApplication(scope.row)">查看详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCompanyStore } from '../../store/company'
import { ElMessage } from 'element-plus'

const router = useRouter()
const companyStore = useCompanyStore()

const stats = ref({
  publishedPositions: 0,
  activePositions: 0,
  totalApplications: 0,
  currentInterns: 0
})

const recentApplications = ref([])

// 获取统计数据
const fetchDashboardStats = async () => {
  try {
    // 获取岗位统计数据
    const positionsResponse = await companyStore.fetchPositions({ page: 0, size: 1000 });
    const positions = positionsResponse.content || positionsResponse;

    // 计算发布岗位数（所有状态的岗位）
    stats.value.publishedPositions = positions.length;

    // 计算当前实习岗位数（已上线状态的岗位）
    stats.value.activePositions = positions.filter(p => p.status === 1).length;

    // 获取申请统计数据
    const applicationsResponse = await companyStore.fetchApplications({ page: 0, size: 1000 });
    const applications = applicationsResponse.content || applicationsResponse;

    // 计算收到申请数
    stats.value.totalApplications = applications.length;

    // 计算在岗实习生数（进行中状态的实习）
    const internshipsResponse = await companyStore.fetchCompanyInternships({ page: 0, size: 1000 });
    const internships = internshipsResponse.content || internshipsResponse;
    stats.value.currentInterns = internships.filter(i => i.status === 1).length;
  } catch (error) {
    ElMessage.error('获取统计数据失败: ' + (error.response?.data?.message || error.message));
  }
}

// 获取最近申请
const fetchRecentApplications = async () => {
  try {
    // 获取所有申请，按申请时间倒序排列
    const response = await companyStore.fetchApplications({
      page: 0,
      size: 10,
      sort: 'appliedAt,desc'
    });

    const allApplications = response.content || response;

    // 优先展示未处理的申请（status === 0）
    const pendingApplications = allApplications.filter(app => app.status === 0);

    // 如果有未处理的申请，优先展示这些申请
    if (pendingApplications.length > 0) {
      // 取前3条未处理的申请
      recentApplications.value = pendingApplications.slice(0, 3);
    } else {
      // 如果没有未处理的申请，则展示最近的3条申请
      recentApplications.value = allApplications.slice(0, 3);
    }
  } catch (error) {
    ElMessage.error('获取最近申请失败: ' + (error.response?.data?.message || error.message));
  }
}

// 导航到指定路径
const navigateTo = (path) => {
  router.push(path)
}

// 添加新的导航方法
const navigateToApplication = (application) => {
  router.push(`/company/applications`)
}
// 查看申请详情
const viewApplication = (application) => {
  router.push(`/company/applications/${application.id}`)
}

// 获取申请状态类型
const getApplicationStatusType = (status) => {
  switch (status) {
    case 0: return 'info'   // 待处理
    case 1: return 'success' // 已接受
    case 2: return 'danger' // 已拒绝
    case 3: return 'warning' // 已取消
    default: return ''
  }
}

// 获取申请状态标签
const getApplicationStatusLabel = (status) => {
  switch (status) {
    case 0: return '待处理'
    case 1: return '已接受'
    case 2: return '已拒绝'
    case 3: return '已取消'
    default: return '未知'
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

onMounted(() => {
  fetchDashboardStats()
  fetchRecentApplications()
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.actions-section {
  margin-bottom: 20px;
}

.quick-actions {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.card-header {
  font-weight: bold;
}

.recent-applications {
  margin-top: 20px;
}
</style>
